package com.zhangfb95.crosschain.plugin.container.java.fabric2.service.impl;

import com.zhangfb95.crosschain.plugin.container.java.fabric2.infra.config.properties.FabricProperties;
import com.zhangfb95.crosschain.plugin.container.java.fabric2.infra.model.controller.dto.ChainPathInfo;
import com.zhangfb95.crosschain.plugin.container.java.fabric2.service.ChainPathService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangfubing
 * @since 2023/12/1
 */
@Component
public class ChainPathServiceImpl implements ChainPathService {

    @Autowired
    private FabricProperties fabricProperties;

    @Override
    public ChainPathInfo build(String chainPath) {
        String chainName = null;
        String channelName = null;
        String chaincodeName = null;
        if (chainPath.startsWith(fabricProperties.getChainName())) {
            chainName = fabricProperties.getChainName();
            String suffix = chainPath.substring(fabricProperties.getChainName().length());
            if (suffix.startsWith(".")) {
                int channelPosition = 1;
                int chaincodePosition = suffix.indexOf(".", channelPosition);
                if (chaincodePosition < 0) {
                    channelName = suffix.substring(channelPosition);
                } else {
                    channelName = suffix.substring(channelPosition, chaincodePosition);
                    chaincodeName = suffix.substring(chaincodePosition + 1);
                }
            }
        }

        return new ChainPathInfo().setChainName(chainName)
                .setChannelName(channelName)
                .setChaincodeName(chaincodeName);
    }
}
